<?php


namespace SidToken\Model;


use SidToken\Utils\TrxRpc;
use Think\Model;

class SidTransferLogModel extends Model
{
    const STATUS_UNCHECK = 0;
    const STATUS_SUCCESS = 1;
    const STATUS_FAIL = 2;

    public function createOrder($symbol, $type, $uid, $from, $to, $txid, $amount, $reason = '', $status = self::STATUS_UNCHECK)
    {
        $data = [
            'symbol' => $symbol,
            'type' => $type,
            'uid' => $uid,
            'from' => $from,
            'to' => $to,
            'txid' => $txid,
            'amount' => $amount,
            'create_time' => time(),
            'reason' => $reason,
            'status' => $status
        ];

        $id = $data['id'] = $this->add($data);
        return $data;
    }

    /**
     * 根据txid获取数据
     * @param $txid
     * @return mixed
     */
    public function getDataByTxid($txid)
    {
        $key = "transferlog_txid{$txid}";
        $data = S($key);
        if (!$data) {
            $data = $this->where(['txid' => $txid])->find();
            if ($data) {
                S($key, $data);
            }
        }
        return $data;
    }

    /**
     * 判断txid是否存在
     * @param $txid
     * @return bool
     */
    public function isTxidExist($txid)
    {
        $data = $this->getDataByTxid($txid);
        return $data != null;
    }

    /**
     * 批量添加转账记录
     * @param $uids
     * @param $symbol
     * @param $type inc|dec
     * @param $from
     * @param $to
     * @param $txid
     * @param $amount
     * @param string $reason
     * @param int $status
     * @return bool
     */
    public function addTransferLogs($uids, $symbol, $type, $from, $to, $txid, $amount, $reason = '', $status = self::STATUS_UNCHECK)
    {
        $uids = is_array($uids) ? $uids : explode(',', $uids);

        foreach ($uids as $uid) {
            $data = [
                'symbol' => $symbol,
                'type' => $type == 'inc' ? strtoupper($symbol) . "转入" : strtoupper($symbol) . "转出",
                'uid' => $uid,
                'from' => $from,
                'to' => $to,
                'txid' => $txid,
                'amount' => $amount,
                'create_time' => time(),
                'reason' => $reason,
                'status' => $status
            ];
            $this->add($data);
        }
        return true;
    }


    public function statusStr($status)
    {
        if ($status == self::STATUS_FAIL) {
            return "失败";
        } else if ($status == self::STATUS_SUCCESS) {
            return "成功";
        } else {
            return "待审核";
        }
    }
}